<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 编辑用户组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Users_Edit extends Widget_Abstract_Users implements Widget_Interface_Do
{
    /**
     * 获取页面偏移的URL Query
     *
     * @access protected
     * @param integer $uid 用户id
     * @return string
     */
    protected function getPageOffsetQuery($uid)
    {
        return 'page=' . $this->getPageOffset('uid', $uid);
    }

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        /** 管理员以上权限 */
        $this->user->pass('admin');
		
        /** 更新模式 */
        if (!empty($this->request->uid) && 'delete' != $this->request->do) {
            $this->select()
                ->where('uid = ?', $this->request->filter('int')->uid)
			    ->limit(1)
			    ->fetchRow(array($this, 'push'));

            if (!$this->have()) {
                throw new Widget_Exception(_t('用户不存在'), 404);
            }
        }
    }

    /**
     * 获取菜单标题
     *
     * @access public
     * @return string
     */
    public function getMenuTitle()
    {
        if (isset($this->request->uid)) {
            if (!empty($this->name)) {
                return _t('编辑用户 %s', $this->name);
            }
        } else {
            return _t('增加用户');
        }

        throw new Widget_Exception(_t('用户不存在'), 404);
    }

    /**
     * 判断用户是否存在
     *
     * @access public
     * @param integer $uid 用户主键
     * @return boolean
     */
    public function userExists($uid)
    {
        $user = $this->db->select(1)
		    ->from('table.users')
            ->where('uid = ?', $uid)
			->limit(1)
			->fetchRow();

        return !empty($user);
    }

    /**
     * 生成表单
     *
     * @access public
     * @param string $action 表单动作
     * @return Form
     */
    public function form()
    {
        /** 构建表格 */
        $form = new Form($this->security->actionUrl('users-edit', false));

        /** 用户名称 */
        $name = new Form_Text('name', NULL, NULL, _t('用户名 *'), _t('此用户名将作为用户登录时所用的名称.')
            . '<br />' . _t('请不要与系统中现有的用户名重复.'));
        $form->addInput($name);

        /** 电子邮箱地址 */
        $mail = new Form_Text('mail', NULL, NULL, _t('电子邮箱地址 *'), _t('电子邮箱地址将作为此用户的主要联系方式.')
            . '<br />' . _t('请不要与系统中现有的电子邮箱地址重复.'));
        $form->addInput($mail);

        /** 用户昵称 */
        $nickName = new Form_Text('nickName', NULL, NULL, _t('用户昵称'), _t('用户昵称可以与用户名不同, 用于前台显示.')
            . '<br />' . _t('如果你将此项留空, 将默认使用用户名.'));
        $form->addInput($nickName);

        /** 用户密码 */
        $password = new Form_Password('password', NULL, NULL, _t('用户密码'), _t('为此用户分配一个密码.')
            . '<br />' . _t('建议使用特殊字符与字母、数字的混编样式,以增加系统安全性.'));
        $form->addInput($password);

        /** 用户密码确认 */
        $confirm = new Form_Password('confirm', NULL, NULL, _t('用户密码确认'), _t('请确认你的密码, 与上面输入的密码保持一致.'));
        $form->addInput($confirm);

        /** 用户组 */
        $group =  new Form_Select('group', $this->user->groups[0],
                NULL, _t('用户组'), _t('不同的用户组拥有不同的权限.'));
        $form->addInput($group);

        /** 个人主页 */
        $url = new Form_Text('url', NULL, NULL, _t('个人主页'));
        $form->addInput($url);

        /** 签名 */
        $sign = new Form_Textarea('sign', NULL, NULL, _t('签名'));
        $form->addInput($sign);
		$sign->input->setAttr('style', 'min-height: 80px;');

        /** 简介 */
        $intro =  new Form_Textarea('intro', NULL, NULL, _t('简介'));
        $form->addInput($intro);
		$intro->input->setAttr('style', 'min-height: 120px;');
		
        /** 用户动作 */
        $do = new Form_Hidden('do');
        $form->set($do);

        /** 用户主键 */
        $uid = new Form_Hidden('uid');
        $form->addInput($uid);

        /** 提交按钮 */
        $submit = new Form_Submit();
        $form->set($submit);

        if ($this->uid) {
            $submit->value(_t('编辑用户'));
            $name->value($this->name);
            $nickName->value($this->nickName);
            $mail->value($this->mail);
            $group->value($this->group);
            $do->value('update');
            $uid->value($this->uid);
            $url->value($this->url);
            $sign->value($this->sign);
            $intro->value($this->intro);
        } else {
            $submit->value(_t('增加用户'));
            $do->value('insert');
        }

        /** 给表单增加规则 */
        $nickName->addRule(array($this, 'nickNameExists'), _t('昵称已经存在'));
        $nickName->addRule('xssCheck', _t('请不要在昵称中使用特殊字符'));
        $mail->addRule('required', _t('必须填写电子邮箱'));
        $mail->addRule(array($this, 'mailExists'), _t('电子邮箱地址已经存在'));
        $mail->addRule('email', _t('电子邮箱格式错误'));
        $password->addRule('minLength', _t('为了保证账户安全, 请输入至少六位的密码'), 6);
        $confirm->addRule('confirm', _t('两次输入的密码不一致'), 'password');
        $url->addRule('url', _t('个人主页地址格式错误'));
        $sign->addRule('xssCheck', _t('请不要在签名中使用特殊字符'));
        $intro->addRule('xssCheck', _t('请不要在简介中使用特殊字符'));
		
		/** 增加用户 */
        if (!$this->uid) {
            $name->addRule('required', _t('必须填写用户名称'));
            $name->addRule('xssCheck', _t('请不要在用户名中使用特殊字符'));
            $name->addRule(array($this, 'nameExists'), _t('用户名已经存在'));
            $password->label(_t('用户密码 *'));
            $confirm->label(_t('用户密码确认 *'));
            $password->addRule('required', _t('必须填写密码'));
        }

		/** 更新用户 */
        if ($this->uid) {
            $name->input->setAttr('disabled', 'disabled');
            $uid->addRule('required', _t('用户主键不存在'));
            $uid->addRule(array($this, 'userExists'), _t('用户不存在'));
        }

		/** 插件接口 */
		//HOOK PLUG_User_Form($form, $this);
		
        return $form;
    }

    /**
     * 增加用户
     *
     * @access public
     * @return void
     */
    public function insertUser($values = array())
    {
		/** 插件接口 */
		//HOOK $values | PLUG_User_Insert($values, $this);

        /** 插入数据 */
        $insertId = $this->insert($values);

        $this->select()
		    ->where('table.users.uid = ?', $insertId)
			->limit(1)
			->fetchRow(array($this, 'push'));
		
		/** 插件接口 */
		//HOOK PLUG_User_Insert_Success($this);
		
		return $insertId;
    }

    /**
     * 更新用户
     *
     * @access public
     * @return void
     */
    public function updateUser($values = array())
    {
		if (!$this->have()) {
		    return ;
		}

		/** 插件接口 */
		//HOOK $values | PLUG_User_Update($values, $this);
		
		$uid = $this->uid;
		
        /** 更新数据 */
        $updateRows = $this->update($uid, $values);

        $this->select()
		    ->where('table.users.uid = ?', $uid)
			->limit(1)
			->fetchRow(array($this, 'push'));
		
		/** 插件接口 */
		//HOOK PLUG_User_Update_Success($this);
		
		return $updateRows;
    }

    /**
     * 删除用户
     *
     * @access public
     * @return void
     */
    public function deleteUser($uid)
    {
		$deleteRows = false;
        $masterUserId = $this->db->select(array('MIN(uid)' => 'masterUserId'))
		    ->from('table.users')
			->fetchObject()
			->masterUserId;
		$user = $this->select()
			->where('uid = ?', $uid)
			->limit(1)
			->fetchRow(array($this, 'push'));
		
        if ($user && ($masterUserId != $uid) && ($uid != $this->user->uid)) {

			$Widget_Contents_Post_Edit = $this->widget('Widget_Contents_Post_Edit');
			$Widget_Contents_Page_Edit = $this->widget('Widget_Contents_Page_Edit');
			$max = 0;
            while (1) {
                $arrlist = $this->db->select('cid', 'type')
				    ->from('table.contents')
			        ->where('uid = ?', $uid)
					->where('cid > ?', $max)
				    ->limit(1000)
				    ->fetchAll();
				
                if (empty($arrlist)) {
                    break;
                }

                foreach ($arrlist as $value) 
				{
					$value['cid'] > $max && $max = $value['cid'];
		            'post' == $value['type'] && $Widget_Contents_Post_Edit->deletePost($value['cid']);
		            'page' == $value['type'] && $Widget_Contents_Page_Edit->deletePage($value['cid']);
		        }
            }	
			
            /** 插件接口 */
            //HOOK PLUG_User_Delete($this);
			
            $deleteRows = $this->delete($uid);

            /** 插件接口 */
            //HOOK PLUG_User_Delete_Success($this);
			
	    }
		return $deleteRows;
    }

    public function operate()
    {
		$buttons = array();

		$buttons[] = Helper::element('a', _t('全选'), array(
		    'data-selectall'=>NULL,
			'href'=>'javascript:void(0);'
			)
		);

		$buttons[] = Helper::element('a', _t('删除'), array(
		    'href'=>'javascript:void(0);',
		    'data-action'=>$this->security->actionUrl('users-edit?do=delete', false),
			'data-confirm'=>_t('删除不可恢复，确定删除？'),
			'data-item'=>'uid',
			'style'=>'color:red'
			)
		);
		
		/** 插件接口 */
		//HOOK $buttons[] | PLUG_User_Operate($this);

		return $this->widget('Widget_Operate')->render($buttons);
    }
	
    /**
     * 入口函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->user->pass('admin');
        $this->security->protect();
		
        switch ($this->request->do) {
            case 'insert':
			
				$form = $this->form();
			    
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }

                $user = $this->request->from(array_keys($form->getInputs()));
                $user['nickName'] = empty($user['nickName']) ? $user['name'] : $user['nickName'];
                $user['created'] = $this->options->time;

		        $this->insertUser($user);
			
                /** 提示信息 */
                $this->result->set(0, _t('用户 %s 增加成功', $this->nickName), array('location'=>$this->options->ucenterUrl('users', false), 'uid'=>$this->uid));
				
            break;
            case 'update':
			
				$form = $this->form();
			    
		        /** 验证格式 */
                if ($message = $form->validate()) {
                    $this->result->set(key($message), current($message));
                }

                $users = $this->request->from(array_keys($form->getInputs()));

                $users['nickName'] = empty($users['nickName']) ? $this->name : $users['nickName'];
				
				/** 不允许修改用户名 */
				unset($users['name']);
				
                if (empty($users['password'])) {
                    unset($users['password']);
                }
				
		        $this->updateUser($users);
			
                /** 提示信息 */
                $this->result->set(0, _t('用户 %s 更新成功', $this->nickName), array('location'=>$this->options->ucenterUrl('users?' . $this->getPageOffsetQuery($this->request->uid), false), 'uid'=>$this->uid));

            break;

            case 'delete':
			
                $uids = $this->request->filter('int')->getArray('uid');
                $deleteRows = array();

                foreach ($uids as $uid) {
		            if($this->deleteUser($uid)){ 
					    $deleteRows[] = $uid;
					}
                }

                /** 设置提示信息 */
                $this->result->set(
				    $deleteRows ? 0 : 1, 
				    $deleteRows ? _t('成功删除 %s 个用户', count($deleteRows)) : _t('没有用户被删除'),
				    $deleteRows
				);
				
            break;
        }
		$this->result->set(404, _t('请求的资源不存在'));
    }
}
